<!--凭证主表-->
<script setup lang="ts">
    import {AxiosPromise} from "axios";

    defineOptions({
        name: "Voucher",
        inheritAttrs: false,
    });

    import {ElLoading, UploadFile} from "element-plus";
		import {watch} from "vue";
		import {
			getSysVoucherPage,
			getSysVoucherForm,
			saveSysVoucher,
			deleteSysVoucher,
			importSysVoucher,
			exportSysVoucher,
			generate,
			getItems
		} from "@/api/voucher";
		import { getCompanyList } from "@/api/company";

    const queryFormRef = ref(ElForm);
    const dataFormRef = ref(ElForm);
    const importRef = ref(ElForm);

    const loading = ref(false);
    const itemLoading = ref(false);
    const ids = ref<number[]>([]);
    const total = ref(0);
    const itemTotal = ref(0);
    const voucherId = ref<any>();
		const detailInfoVisible = ref(false);
		const detailTableHeight = ref(650)

    const queryParams = reactive<any>({
        pageNum: 1,
        pageSize: 20,
    });
    const itemQueryParams = reactive<any>({
        pageNum: 1,
        pageSize: 20,
    });
		const generateParams = reactive<any>({})

    const sysVoucherList = ref<[]>([]);
    const companyList = ref<[]>([]);
    const voucherItemList = ref<[]>([]);

    const dialog = reactive<DialogOption>({
        visible: false,
    });
    const importDialog = reactive<DialogOption>({
        title: "生成凭证",
        visible: false,
    });

    const excelFile = ref<File>();
    const excelFilelist = ref<File[]>([]);
    const formData = reactive<any>({});

    const generateRules = reactive({
        month: [{ required: true, message: "请选择年月", trigger: "change" }],
        companyCode: [{ required: true, message: "请选择入账主体", trigger: "change" }],
    });
		// 通过监视详情信息div状态，改变详情表格的高度
		watch(detailInfoVisible, (value) => {
			if (value) {
				detailTableHeight.value = 300
			}else{
				detailTableHeight.value = 650
			}
		});



    /**
     * 查询
     */
    function handleQuery() {
        loading.value = true;
				queryParams.voucherYear = queryParams.month.split('-')[0]
				queryParams.voucherMonth = queryParams.month.split('-')[1]
        getSysVoucherPage(queryParams)
            .then(({ data }) => {
                sysVoucherList.value = data.list;
                total.value = data.total;
            })
            .finally(() => {
                loading.value = false;
            });
    }

    /**
     * 重置查询
     */
    function resetQuery() {
        queryFormRef.value.resetFields();
        queryParams.pageNum = 1;
        handleQuery();
    }

    /**
     * 行checkbox change事件
     */
    function handleSelectionChange(selection: any) {
        ids.value = selection.map((item: any) => item.id);
    }

    /**
     * 打开字典类型表单弹窗
     *
     * @param dicTypeId 字典类型ID
     */
    function openDialog(id?: number) {
        dialog.visible = true;
        if (id) {
            dialog.title = "修改凭证主表";
            getSysVoucherForm(id).then(({ data }) => {
                Object.assign(formData, data);
            });
        } else {
            dialog.title = "新增凭证主表";
        }
    }

    /**
     * 字典类型表单提交
     */
    function handleSubmit() {
        dataFormRef.value.validate((isValid: boolean) => {
            if (isValid) {
                loading.value = false;
                saveSysVoucher(formData)
                    .then(() => {
                        ElMessage.success("保存成功");
                        closeDialog();
                        handleQuery();
                    })
                    .finally(() => (loading.value = false));
            }
        });
    }

    /**
     * 关闭弹窗
     */
    function closeDialog() {
        dialog.visible = false;
        resetForm();
    }

    /**
     * 重置表单
     */
    function resetForm() {
        dataFormRef.value.resetFields();
        dataFormRef.value.clearValidate();

        formData.id = undefined;
    }

    /**
     * 删除凭证主表
     */
    function handleDelete(id?: number) {
        const dictTypeIds = [id || ids.value].join(",");
        if (!dictTypeIds) {
            ElMessage.warning("请勾选删除项");
            return;
        }

        ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            deleteSysVoucher(dictTypeIds).then(() => {
                ElMessage.success("删除成功");
                resetQuery();
            });
        });
    }

    /** 打开导入弹窗 */
    async function openImportDialog() {
        importDialog.visible = true;
				getAllCompanyList()
    }

    /**
     * Excel文件change事件
     *
     * @param file
     */
    function handleExcelChange(file: UploadFile) {
        if (file.size !== undefined) {
            if (file.size > 20*1024*1024) {
                ElMessage.warning("上传文件大小不能超过20M");
                return false
            }
        }
        if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
            ElMessage.warning("上传Excel只能为xlsx、xls格式");
            excelFile.value = undefined;
            excelFilelist.value = [];
            return false;
        }
        excelFile.value = file.raw;
    }

    /** 生成凭证提交 */
    function handleGenerate() {
			importRef.value.validate((isValid: boolean) => {
				if (isValid) {
					generate(generateParams.month, generateParams.companyCode)
					closeImportDialog();
					ElMessage.success('生成成功，请稍后刷新');
					resetQuery();
				}
			})
    }

    /**  关闭导入弹窗 */
    function closeImportDialog() {
        importDialog.visible = false;
				generateParams.month = ''
				generateParams.companyCode = ''
    }

    /** 导出凭证主表 */
    function handleExport() {
				queryParams.voucherYear = queryParams.month.split('-')[0]
				queryParams.voucherMonth = queryParams.month.split('-')[1]
        exportSysVoucher(queryParams.voucherYear, queryParams.voucherMonth).then((response: any) => {
            const blob = new Blob([response.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
            });
            const a = document.createElement("a");
            const href = window.URL.createObjectURL(blob); // 下载的链接
            a.href = href;
            a.download = decodeURI(
                response.headers["content-disposition"].split(";")[1].split("=")[1]
            ); // 获取后台设置的文件名称
            document.body.appendChild(a);
            a.click(); // 点击导出
            document.body.removeChild(a); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
        });
    }

		/**
		 * 获取入账主体列表
		 *
		 */
		function getAllCompanyList() {
			getCompanyList().then((response) => {
				companyList.value = response.data;
			});
		}

		function rowClick(row: any, column: any, event: any){
			// 查询明细
			detailInfoVisible.value = true
			itemQueryParams.pageNum = 1
			voucherId.value = row.id
			voucherItemList.value = []
			handleQueryItem()
		}

		function handleQueryItem() {
			voucherItemList.value = []
			itemLoading.value = true
			getItems(voucherId.value, itemQueryParams).then(({data}) => {
				itemTotal.value = data.total;
				voucherItemList.value = data.list
			}).finally(() => itemLoading.value = false)
		}

    onMounted(() => {
				let now = new Date()
				let month = now.getMonth()
				let nowMonth;
				if (month < 9){
					nowMonth = now.getFullYear() + '-0' + (now.getMonth() + 1) + ''
				}	else {
					nowMonth = now.getFullYear() + '-' + (now.getMonth() + 1) + ''
				}
				queryParams.month = nowMonth
        handleQuery();
    });
</script>

<template>
    <div class="app-container">
          <el-card shadow="never">
            <template #header>
                <div class="flex justify-between">
                    <div>
											年月
											<el-date-picker
												v-model="queryParams.month"
												style="width: 200px"
												type="month"
												placeholder="年月"
												value-format="YYYY-MM"
												:clearable="false"
											/>
											<el-button type="primary" @click="handleQuery()"
											><i-ep-search />搜索</el-button
											>
                    </div>
                    <div>
                        <el-button type="danger" @click="openImportDialog" v-hasPerm="['sys:voucher:generate']"
                        >生成凭证</el-button
                        >
                        <el-button class="ml-3" @click="handleExport" v-hasPerm="['sys:voucher:export']"
                        ><template #icon><i-ep-download /></template>导出</el-button
                        >
                    </div>
                </div>
            </template>
            <el-table
                    v-loading="loading"
                    :height="sysVoucherList && sysVoucherList.length > 0 ? detailTableHeight : 300"
                    size="small"
                    :header-row-style="{color: 'dimgray'}"
                    highlight-current-row
                    :data="sysVoucherList"
                    border
                    @selection-change="handleSelectionChange"
										@row-click="rowClick"
            >
                <el-table-column type="selection" width="40" align="center" show-overflow-tooltip />
                <el-table-column label="*单据头(序号)" width="100" show-overflow-tooltip/>
                <el-table-column label="*(单据头)账簿#编码" prop="accountBookId" width="140" show-overflow-tooltip/>
                <el-table-column label="(单据头)账簿#名称" prop="accountBookName" width="140" show-overflow-tooltip/>
                <el-table-column label="*(单据头)日期" prop="voucherDate" width="100" show-overflow-tooltip/>
                <el-table-column label="(单据头)业务日期" prop="businessDate" width="120" show-overflow-tooltip/>
                <el-table-column label="(单据头)会计年度" prop="voucherYear" width="120" show-overflow-tooltip/>
                <el-table-column label="(单据头)期间" prop="voucherMonth" width="100" show-overflow-tooltip/>
                <el-table-column label="*(单据头)凭证字#编码" width="140" show-overflow-tooltip/>
                <el-table-column label="(单据头)凭证字#名称" width="140" show-overflow-tooltip/>
                <el-table-column label="*(单据头)凭证号" width="120" show-overflow-tooltip/>
                <el-table-column label="(单据头)核算组织#编码" prop="orgId" width="140" show-overflow-tooltip/>
                <el-table-column label="(单据头)核算组织#名称" prop="orgName" width="140" show-overflow-tooltip/>
                <el-table-column label="创建人" prop="createByName" width="100" show-overflow-tooltip/>
                <el-table-column label="创建时间" prop="createTime" width="140" show-overflow-tooltip/>
            </el-table>

            <pagination
                    v-if="total > 0"
                    v-model:total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="handleQuery"
            />
					<!--凭证明细-->
					<div v-if="detailInfoVisible">
						<div style="width: 98%;float:left;">
							<el-table
								v-loading="itemLoading"
								:height="316"
								size="small"
								:header-row-style="{color: 'dimgray'}"
								highlight-current-row
								:data="voucherItemList"
								border
							>
								<el-table-column label="*分录(序号)" width="80" show-overflow-tooltip/>
								<el-table-column label="(分录)摘要" prop="explanation" width="100" show-overflow-tooltip/>
								<el-table-column label="*(分录)科目编码#编码" prop="lastCode" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)科目编码#名称" prop="firstName" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)科目全名" prop="lastName" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)客户分组#编码" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)客户分组#名称(Null)" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)物料分组#编码" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)物料分组#名称(Null)" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)组织机构#编码" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)组织机构#名称(Null)" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)银行#编码" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.bank.code}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)银行#名称(Null)" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.bank.name}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)税率#编码" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)税率#名称(Null)" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)仓库#编码" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)仓库#名称(Null)" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)银行账号#编码" prop="createByName" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.bankAccount.code}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)银行账号#名称(Null)" prop="createByName" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.bankAccount.name}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)资产类别#编码" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)资产类别#名称(Null)" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)部门#编码" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.dept.code}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)部门#名称(Null)" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.dept.name}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)供应商#编码" prop="createByName" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.supplier.code}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)供应商#名称(Null)" prop="createByName" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.supplier.name}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)客户#编码" prop="createByName" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.customer.code}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)客户#名称(Null)" prop="createByName" width="100" show-overflow-tooltip>
									<template #default="scope">
										{{scope.row.customer.name}}
									</template>
								</el-table-column>
								<el-table-column label="(分录)费用项目#编码" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)费用项目#名称(Null)" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)物料#编码" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)物料#名称(Null)" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)员工#编码" width="100" show-overflow-tooltip/>
								<el-table-column label="(分录)员工#名称(Null)" width="100" show-overflow-tooltip/>
								<el-table-column label="*(分录)币别#编码" width="100" show-overflow-tooltip>
									<template #default="scope">
										PRE001
									</template>
								</el-table-column>
								<el-table-column label="(分录)币别#名称" width="100" show-overflow-tooltip>
									<template #default="scope">
										人民币
									</template>
								</el-table-column>
								<el-table-column label="*(分录)汇率类型#编码" width="100" show-overflow-tooltip>
									<template #default="scope">
										HLTX01_SYS
									</template>
								</el-table-column>
								<el-table-column label="(分录)汇率类型#名称" width="100" show-overflow-tooltip>
									<template #default="scope">
										固定汇率
									</template>
								</el-table-column>
								<el-table-column label="(分录)汇率" width="100" show-overflow-tooltip>
									<template #default="scope">
										1
									</template>
								</el-table-column>
								<el-table-column label="(分录)原币金额" width="100" show-overflow-tooltip>
									<template #default="scope">
										<format-money :value="scope.row.amount"></format-money>
									</template>
								</el-table-column>
								<el-table-column label="(分录)借方金额" prop="createByName" width="100" show-overflow-tooltip>
									<template #default="scope">
										<format-money :value="scope.row.debitAmount"></format-money>
									</template>
								</el-table-column>
								<el-table-column label="(分录)贷方金额" prop="createByName" width="100" show-overflow-tooltip>
									<template #default="scope">
										<format-money :value="scope.row.creditAmount"></format-money>
									</template>
								</el-table-column>
							</el-table>

							<pagination
								v-if="itemTotal > 0"
								v-model:total="itemTotal"
								v-model:page="itemQueryParams.pageNum"
								v-model:limit="itemQueryParams.pageSize"
								@pagination="handleQueryItem"
							/>
						</div>
						<div style="float:right;"><i-ep-close  @click="detailInfoVisible = false"/></div>
					</div>
        </el-card>

        <el-dialog
                v-model="dialog.visible"
                :title="dialog.title"
                width="500px"
                :close-on-click-modal="false"
                @close="closeDialog"
        >
            <el-form
                    ref="dataFormRef"
                    :model="formData"
                    :rules="rules"
                    label-width="150px"
            >
                    <el-form-item label="账簿编码" prop="accountBookId">
                        <el-input v-model="formData.accountBookId" placeholder="请输入账簿编码" clearable/>
                    </el-form-item>
                    <el-form-item label="账簿名称" prop="accountBookName">
                        <el-input v-model="formData.accountBookName" placeholder="请输入账簿名称" clearable/>
                    </el-form-item>
                    <el-form-item label="日期" prop="voucherDate">
                        <el-input v-model="formData.voucherDate" placeholder="请输入日期" clearable/>
                    </el-form-item>
                    <el-form-item label="业务日期" prop="businessDate">
                        <el-input v-model="formData.businessDate" placeholder="请输入业务日期" clearable/>
                    </el-form-item>
                    <el-form-item label="会计年度" prop="voucherYear">
                        <el-input v-model="formData.voucherYear" placeholder="请输入会计年度" clearable/>
                    </el-form-item>
                    <el-form-item label="记账月" prop="voucherMonth">
                        <el-input v-model="formData.voucherMonth" placeholder="请输入记账月" clearable/>
                    </el-form-item>
                    <el-form-item label="核算组织编码" prop="orgId">
                        <el-input v-model="formData.orgId" placeholder="请输入核算组织编码" clearable/>
                    </el-form-item>
                    <el-form-item label="核算组织名称" prop="orgName">
                        <el-input v-model="formData.orgName" placeholder="请输入核算组织名称" clearable/>
                    </el-form-item>
                    <el-form-item label="创建人" prop="createBy">
                        <el-input v-model="formData.createBy" placeholder="请输入创建人" clearable/>
                    </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit">确 定</el-button>
                    <el-button @click="closeDialog">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 生成凭证弹窗 -->
        <el-dialog
                v-model="importDialog.visible"
                :title="importDialog.title"
                width="600px"
                append-to-body
                @close="closeImportDialog"
        >
            <el-form label-width="80px" :rules="generateRules" :model="generateParams" ref="importRef">
							<el-form-item label="年月" prop="month">
								<el-date-picker
									v-model="generateParams.month"
									style="width: 200px"
									type="month"
									placeholder="年月"
									value-format="YYYYMM"
									:clearable="false"
								/>
							</el-form-item>
							<el-form-item label="入账主体" prop="companyCode">
								<el-select v-model="generateParams.companyCode" class="yz-el-select" placeholder="请选择">
									<el-option
										v-for="item in companyList"
										:key="item.code"
										:label="item.name"
										:value="item.code"
									/>
								</el-select>
							</el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleGenerate">确 定</el-button>
                    <el-button @click="closeImportDialog">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
